#include "radiospy.h"
#include <time.h>
#include <cstdlib>
#include <time.h>
#include <cstring>
#include <stdio.h>


main(int argc, char *argv[]) {
	char recfile[255];
	char finfile[255];	
	char timestamp[64];	
	char data[2];
	FILE *mic;
	FILE *rec;
	FILE *thr;
	void *bufp;
	bufp=data;
	int val;
	int thresh=0;
	bool sound;
	int input;
	size_t i;
	struct tm tim;
	
	if (!(mic=fopen(dsp_to_use,"r"))) {
		printf("Could not open %s. Make sure you've got it set in Duplex mode and that the user you're running this program with is a member of the 'audio' group.\n", dsp_to_use);
		exit(0);
	}
		
	if (!(thr=fopen("threshold.bin","r"))) {
		printf("Can't open threshold.bin - Please run mictune\n");
		exit(0);
	}

	data[0]=' ';
	data[1]=' ';
	fread(bufp,1,1,thr);	
	thresh =(int)data[0];
	fclose(thr);
	
	printf("RadioSpy V 0.1\n");
	printf("Coded by Jonathan Endersby\n");
	printf("http://www.arbitraryuser.com/blog/\n");			
	printf("Based on original work (DSPSPY) by Richard Svensson\n");
	printf("This Software is GPL \n");
	printf("___________________________\n");
	printf("Using threshold %d \n",thresh);

	for (;;) {
     	
		data[0]=' ';
		data[1]=' ';
		fread(bufp,1,1,mic);	
		val =(int)data[0];	
		
		if (abs(val) <thresh) {
			printf("SOUND detected - ");
			
			fflush(stdout);
						
			time_t now;
			now = time(NULL);
			tim = *(localtime(&now));
			i = strftime(timestamp,30,"%Y_%m_%d_%H:%M:%S", &tim);	
			
			sprintf(recfile, "%s.busy", timestamp);
			sprintf(finfile, "%s.raw", timestamp);		
			
			printf("Creating %s", recfile);			
			fflush(stdout);
			
			if (!(rec=fopen(recfile,"w"))) {
				printf("Could not write to %s", recfile);
			}		
					
			sound=true;
			
                        while (sound==true) {
                                sound=false;
                                for (int i=0;i<=150000;i++) {  //about 27 seconds on a modern processor.
                                        data[0]=' ';
                                        data[1]=' ';
                                        fread(bufp,1,1,mic);    
                                        val = (int)data[0];
                                        if (abs(val)<thresh){ sound=true; };
                                        fwrite(bufp,1,1,rec);
                                }
                        }

			
			printf(" - Recording Complete");
			fclose(rec);
			rename(recfile, finfile);
			printf(" - Saved as %s\n", finfile);

		}		
	}
}
